<script setup lang="ts">
import { useRouter } from "vue-router";
import { onMounted, ref } from "vue";
import MyAxios from "../plugins/myAxios";
import { getCurrentUser } from "@/services/user.ts";
import axios from 'axios';
import type {userType} from "@/model/user";
import myAxios from "../plugins/myAxios";

const router = useRouter();
const sixCode = ref('');
const fileList = ref([] as any[]);
const user = ref<userType>();

const onClickLeft = () => {
  router.back();
};

const onSubmit = async () => {
  const res = await myAxios.post('/update', {
    ubankcard: sixCode.value,
    uname: "",
    uphone:"",
    udepartment: "",
    uclass: "",
    namePrivacy:  "",
    uid: ""
  });
  // @ts-ignore
  if (res.code === 200 && res.data) {
    router.replace("/");
  } else {
    console.error("Update failed");
  }
};

const callBaiduOCR = (base64Image: string) => {
  const apiKey = 'UGZn6t4yHOY0BGcwhTvk7Cp5';
  const secretKey = 'aHC0tqE4Yxj6cpaCWyPXBTYeGLrLshk6';
  const accessToken = '24.136b98c343a02d04be47c5962bb81090.2592000.1711249591.282335-50715863';
  const headers = {
    'Content-Type': 'application/x-www-form-urlencoded',
  };

  const data = new URLSearchParams();
  data.append('image', base64Image);
  data.append('access_token', accessToken);

  axios.post('https://aip.baidubce.com/rest/2.0/ocr/v1/bankcard', data, { headers })
      .then(response => {
        console.log('OCR响应', response.data);
        // 在这里处理响应，更新视图或进行其他逻辑操作
        if (response.data && response.data.result && response.data.result.bank_card_number) {
          const bankCardNumber = response.data.result.bank_card_number.replace(/\s/g, ''); // 去除空格
          sixCode.value = bankCardNumber;
        }
      })
      .catch(error => {
        console.error('OCR请求失败', error);
        // 处理错误，例如提示用户或进行其他错误处理
      });
};

onMounted(async () => {
  const res = await getCurrentUser();
  // @ts-ignore
  if (res?.code === 40100 || res.data == null) {
    router.push({
      path: '/login',
      replace: true,
    });
  }
  // @ts-ignore
  if (res.code === 200) {
    user.value = res.data;
  }
});
const afterRead = (file: { content: string }) => {
  console.log('上传成功', file);
  callBaiduOCR(file.content);
};
</script>

<template>
  <div>
    <van-nav-bar left-text="返回" left-arrow @click-left="onClickLeft" style="--van-nav-bar-text-color: #FFC000;--van-nav-bar-icon-color:#FFC000"></van-nav-bar>
    <div style="text-align: center;margin-top: 50px">
      <van-uploader
          preview-size="60"
          v-model="fileList"
          :max-count="1"
          :after-read="afterRead as any"
      />
    </div>
    <van-form @submit="onSubmit" STYLE="padding-top:5px">
      <van-cell-group inset>
        <van-field
            v-model="sixCode"
            name="SixCode"
            label="校园卡号"
            placeholder="填写校园卡号"
            :rules="[
            { required: true, message: '请正确填写校园卡号' },
            { pattern: /^\d{19}$/, message: '请拍照识别或输入正确的校园卡号' }
          ]"
        />
      </van-cell-group>
      <div style="margin: 20px;">
        <van-button color="#FFC000" plain round block native-type="submit">
          一键绑定
        </van-button>
      </div>
    </van-form>
    <div class="footer">
      <p>校园卡号可在中国农业银行APP复制或拍照识别</p>
    </div>
  </div>
</template>

<style scoped>

.logo img {
  width: 200px;
}
.footer {
  text-align: center;
  color: #C2C2C2;
  font-size: 14px;
}
</style>
